<template>
	<view class="weekly-diary-preview">
		<!-- 顶部周选择显示 -->
		<view class="week-header">
			<view class="week-selector" @click="showWeekPicker = true">
				<text class="week-title">{{ weekTitle }}</text>
				<text class="arrow-down">▼</text>
			</view>
		</view>

		<!-- 周选择弹框 -->
		<view v-if="showWeekPicker" class="week-picker-overlay" @click="showWeekPicker = false">
			<view class="week-picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择周</text>
					<text class="close-btn" @click="showWeekPicker = false">×</text>
				</view>

				<view class="month-navigation">
					<button class="nav-btn" @click="prevMonthPicker">◀</button>
					<text class="month-text">{{ pickerYear }}年{{ pickerMonth }}月</text>
					<button class="nav-btn" @click="nextMonthPicker">▶</button>
				</view>

				<view class="weeks-list">
					<view v-for="(week, index) in pickerWeeks" :key="index" class="week-item"
						:class="{ 'active': isCurrentWeek(week.start) }" @click="selectWeek(week.start)">
						<text class="week-label">{{ week.label }}</text>
						<text class="week-dates">{{ week.dateRange }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 日记本主体 - 增加高度 -->
		<view class="notebook-container">
			<!-- 左侧页面 - 日期列表 -->
			<view class="left-page" @touchstart="handleTouchStart" @touchend="handleTouchEnd"
				@mousedown="handleMouseDown" @mouseup="handleMouseUp">
				<view class="page-header">
					<text class="week-title">{{ weekTitle }}</text>
				</view>

				<view class="date-list">
					<view v-for="(day, index) in weekDays" :key="index" class="date-item"
						:class="{ 'has-content': day.hasContent }" @click="selectDay(day)">
						<view class="flexbox flexbox-between">
							<view class="flexbox">
								<view class="date-number">{{ day.date }}</view>
								<view class="weekday">{{ day.weekday }}</view>
							</view>
							<button class="my-button" @click="achieve(day)"
								v-if="selectedDate.date == day.date && isEdit">完成</button>
						</view>


						<!-- 内容预览 -->
						<view v-if="selectedDate.date == day.date && isEdit">
							<input v-model="content" class="inputbox" />
						</view>
						<view v-else class="content-preview" @click="addWirte(day)">
							<text v-if="day.subContent" class="sub-content">{{ day.subContent }}</text>
							<text v-else class="noContent">暂无小记，点击添加</text>
						</view>
					</view>
				</view>

				<!-- 翻页指示 -->
				<view class="page-turn-hint left">
					<text>▶</text>
				</view>
			</view>

			<!-- 右侧页面 - 内容详情 -->
			<view class="right-page" @touchstart="handleTouchStart" @touchend="handleTouchEnd" v-if="false"
				@mousedown="handleMouseDown" @mouseup="handleMouseUp">
				<view class="page-header">
					<text class="current-date">{{ selectedDate.date }} | {{ selectedDate.weekday }}</text>
				</view>

				<view class="content-area">
					<view v-if="selectedDiary" class="diary-content">
						<text class="title">{{ selectedDiary.title }}</text>
						<text class="content">{{ selectedDiary.content }}</text>

						<!-- 心情和格式标签 -->
						<view class="tags">
							<text class="mood-tag">{{ moodMap[selectedDiary.mood] || '' }}</text>
							<text class="format-tag">{{ selectedDiary.textType === 'markdown' ? 'MD' : 'TXT' }}</text>
						</view>
					</view>

					<view v-else class="empty-state">
						<text class="empty-text">点击左侧日期查看日记</text>
					</view>
				</view>

				<!-- 翻页指示 -->
				<view class="page-turn-hint right">
					<text>◀</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch
	} from 'vue'
	import dayjs from 'dayjs'
	import request from '../../utils/request'
	import {
		useUserStore
	} from '../../store/user'
	import isoWeek from 'dayjs/plugin/isoWeek'
	import weekday from 'dayjs/plugin/weekday'

	dayjs.extend(isoWeek)
	dayjs.extend(weekday)

	const userStore = useUserStore()
	const isEdit = ref(false)
	const content = ref("")
	const addWirte = (day) => {
		content.value = day.subContent
		isEdit.value = true
	}

	const update = async (day) => {
		console.log("update", day, day.recordTime, {
			recordTime: day.recordTime.format("YYYY-MM-DD"),
			des: content.value
		});
		await request.get("/des/updateBydate", {
			recordTime: day.recordTime.format("YYYY-MM-DD"),
			des: content.value
		})
		isEdit.value = false
	}

	const achieve = (day) => {
		update(day).then(() => loadWeeklyData())
	}
	// 响应式数据
	const currentWeekStart = ref(dayjs().startOf('week'))
	const currentYear = ref(dayjs().year())
	const currentMonth = ref(dayjs().month() + 1)
	const selectedDate = ref({
		date: '',
		weekday: ''
	})
	const selectedDiary = ref(null)
	const diaryData = ref([])
	const loading = ref(false)
	const showWeekPicker = ref(false)
	const pickerYear = ref(dayjs().year())
	const pickerMonth = ref(dayjs().month() + 1)

	// 触摸/鼠标事件相关数据
	const touchStartX = ref(0)
	const touchEndX = ref(0)
	const mouseStartX = ref(0)
	const mouseEndX = ref(0)

	// 心情映射
	const moodMap = {
		'happy': '😊',
		'sad': '😢',
		'angry': '😠',
		'excited': '🤩',
		'calm': '😌'
	}

	// 计算属性
	const weekTitle = computed(() => {
		const weekNumber = currentWeekStart.value.isoWeek()
		return `${currentMonth.value}月 第${weekNumber}周`
	})

	const weekDays = computed(() => {
		const days = []
		let currentDate = currentWeekStart.value.clone()

		for (let i = 0; i < 7; i++) {
			const date = currentDate.clone()
			const diary = getDiaryByDate(date)

			days.push({
				recordTime: date,
				date: date.date(),
				weekday: getWeekdayAbbr(i),
				hasContent: !!diary,
				mainContent: diary?.title || '',
				subContent: diary?.des || ''
			})

			currentDate = currentDate.add(1, 'day')
		}

		return days
	})

	// 计算选择器中的周
	const pickerWeeks = computed(() => {
		const weeks = []
		const firstDayOfMonth = dayjs().year(pickerYear.value).month(pickerMonth.value - 1).date(1)
		const lastDayOfMonth = firstDayOfMonth.endOf('month')

		// 找到第一个星期一
		let weekStart = firstDayOfMonth.startOf('week')

		// 生成所有周
		while (weekStart.isBefore(lastDayOfMonth) || weekStart.isSame(lastDayOfMonth, 'day')) {
			const weekEnd = weekStart.clone().add(6, 'day')
			const weekNumber = weekStart.isoWeek()

			weeks.push({
				start: weekStart.clone(),
				end: weekEnd.clone(),
				label: `第${weekNumber}周`,
				dateRange: `${weekStart.format('MM-DD')}至${weekEnd.format('MM-DD')}`
			})

			weekStart = weekStart.add(7, 'day')
		}

		return weeks
	})

	// 方法
	const getWeekdayAbbr = (index) => {
		const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
		return weekdays[index]
	}

	const getDiaryByDate = (date) => {
		// 根据日期从diaryData中查找对应的日记
		return diaryData.value.find(d => dayjs(d.recordTime).isSame(date, 'day'))
	}


	const selectDay = (day) => {
		selectedDate.value = {
			...day
		}
		selectedDiary.value = getDiaryByDate(dayjs(`${currentYear.value}-${currentMonth.value}-${day.date}`))
	}

	// 月份切换功能（用于选择器）
	const prevMonthPicker = () => {
		const prevMonthDate = dayjs().year(pickerYear.value).month(pickerMonth.value - 1).subtract(1, 'month')
		pickerYear.value = prevMonthDate.year()
		pickerMonth.value = prevMonthDate.month() + 1
	}

	const nextMonthPicker = () => {
		const nextMonthDate = dayjs().year(pickerYear.value).month(pickerMonth.value - 1).add(1, 'month')
		pickerYear.value = nextMonthDate.year()
		pickerMonth.value = nextMonthDate.month() + 1
	}

	// 选择特定周
	const selectWeek = (weekStart) => {
		currentWeekStart.value = weekStart.clone()
		updateYearAndMonth()
		showWeekPicker.value = false
		loadWeeklyData()
	}

	// 检查是否为当前周
	const isCurrentWeek = (weekStart) => {
		return weekStart.isSame(currentWeekStart.value, 'week')
	}

	// 更新年份和月份
	const updateYearAndMonth = () => {
		currentYear.value = currentWeekStart.value.year()
		currentMonth.value = currentWeekStart.value.month() + 1
	}

	// 加载周数据
	const loadWeeklyData = async () => {
		try {
			loading.value = true
			const startDate = currentWeekStart.value.format('YYYY-MM-DD')
			const endDate = currentWeekStart.value.clone().add(6, 'day').format('YYYY-MM-DD')

			const response = await request.get(
				`/des/weekly?userId=${userStore.id}&startDate=${startDate}&endDate=${endDate}`)

			if (response.code === 200) {
				diaryData.value = response.data || []
			}
		} catch (error) {
			console.error('加载周数据失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 触摸事件处理
	const handleTouchStart = (e) => {
		touchStartX.value = e.touches[0].clientX
	}

	const handleTouchEnd = (e) => {
		touchEndX.value = e.changedTouches[0].clientX
		handleSwipe()
	}

	// 鼠标事件处理
	const handleMouseDown = (e) => {
		mouseStartX.value = e.clientX
	}

	const handleMouseUp = (e) => {
		mouseEndX.value = e.clientX
		handleSwipe()
	}

	// 处理滑动操作
	const handleSwipe = () => {
		const touchDiff = touchEndX.value - touchStartX.value
		const mouseDiff = mouseEndX.value - mouseStartX.value

		// 判断是触摸还是鼠标事件
		const diff = touchDiff || mouseDiff

		// 设置最小滑动距离阈值
		const minSwipeDistance = 50

		// 向左滑动 - 切换到下周
		if (diff < -minSwipeDistance) {
			nextWeek()
		}
		// 向右滑动 - 切换到上周
		else if (diff > minSwipeDistance) {
			prevWeek()
		}
	}

	// 周切换功能
	const prevWeek = () => {
		currentWeekStart.value = currentWeekStart.value.subtract(7, 'day')
		updateYearAndMonth()
		loadWeeklyData()
	}

	const nextWeek = () => {
		currentWeekStart.value = currentWeekStart.value.add(7, 'day')
		updateYearAndMonth()
		loadWeeklyData()
	}

	// 页面加载时获取数据
	onMounted(() => {
		loadWeeklyData()
	})
</script>

<style scoped lang="scss">
	.weekly-diary-preview {
		background-color: #f9f9f9;
		min-height: 100vh;
		padding: 30rpx 0;
		box-sizing: border-box;
		font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
	}

	.week-header {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.week-selector {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border: 1rpx solid #ddd;
		border-radius: 50rpx;
		padding: 15rpx 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		cursor: pointer;
	}

	.week-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-right: 10rpx;
	}

	.arrow-down {
		font-size: 20rpx;
		color: #999;
	}

	/* 周选择弹框样式 */
	.week-picker-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.week-picker-content {
		background-color: #fff;
		border-radius: 20rpx;
		width: 80%;
		max-width: 500rpx;
		max-height: 80vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.picker-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		font-size: 40rpx;
		color: #999;
		cursor: pointer;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.month-navigation {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 20rpx;
		padding: 20rpx 0;
	}

	.month-navigation .nav-btn {
		background-color: #f5f5f5;
		border: none;
		border-radius: 50%;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #666;
	}

	.month-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.weeks-list {
		padding: 0 20rpx 20rpx;
		overflow-y: auto;
		flex: 1;
	}

	.week-item {
		padding: 20rpx;
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		margin-bottom: 15rpx;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.week-item:hover {
		background-color: #f5f5f5;
		border-color: #ddd;
	}

	.week-item.active {
		background-color: #e6f7ff;
		border-color: #1890ff;
	}

	.week-label {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 5rpx;
	}

	.week-dates {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	.notebook-container {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
		position: relative;
		width: 90%;
		max-width: 680rpx;
		height: 1100rpx;
		/* 增加高度 */
		margin: 0 auto 20rpx;
		user-select: none;
		/* 防止拖拽时选中文本 */
	}

	.left-page {
		width: 320rpx;
		height: 1050rpx;
		/* 增加高度 */
		background-color: white;
		border-radius: 10rpx 0 0 10rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
		position: relative;
		z-index: 2;
		cursor: pointer;
	}

	.right-page {
		width: 320rpx;
		height: 1050rpx;
		/* 增加高度 */
		background-color: white;
		border-radius: 0 10rpx 10rpx 0;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
		position: relative;
		z-index: 1;
		cursor: pointer;
	}

	.page-header {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.week-title {
		font-size: 24rpx;
		color: #666;
		text-align: left;
	}

	.current-date {
		font-size: 24rpx;
		color: #666;
		text-align: right;
	}

	.date-list {
		padding: 20rpx;
		height: calc(100% - 60rpx);
		overflow-y: auto;
	}

	.date-item {
		min-height: 108rpx;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #eee;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.date-item:hover {
		background-color: #f5f5f5;
	}

	.date-item.has-content {
		background-color: #f9f9f9;
	}

	.date-number {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 5rpx;
		margin-right: 5rpx;
	}

	.weekday {
		font-size: 20rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.content-preview {
		margin-top: 5rpx;
	}

	.main-content {
		font-size: 22rpx;
		color: #333;
		line-height: 1.4;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.sub-content {
		font-size: 12px;
		color: #666;
		margin-top: 5rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.content-area {
		padding: 20rpx;
		height: calc(100% - 60rpx);
		overflow-y: auto;
	}

	.diary-content {
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.content {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 15rpx;
		display: block;
		white-space: pre-wrap;
	}

	.tags {
		display: flex;
		gap: 10rpx;
		font-size: 18rpx;
	}

	.mood-tag {
		color: #666;
	}

	.format-tag {
		color: #999;
	}

	.empty-state {
		text-align: center;
		padding: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.empty-text {
		font-size: 24rpx;
		color: #999;
	}

	.artistic-text {
		font-size: 32rpx;
		font-weight: 500;
		color: #666;
		letter-spacing: 2rpx;
		margin-bottom: 10rpx;
	}

	.artistic-subtext {
		font-size: 24rpx;
		color: #999;
		opacity: 0.8;
		font-style: italic;
	}

	/* 模拟笔记本的立体效果 */
	.notebook-container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, #e6d9d0 0%, #f0e8df 100%);
		border-radius: 10rpx;
		z-index: 0;
		opacity: 0.8;
	}

	.flexbox {
		display: flex;
		align-items: baseline;

		&-between {
			justify-content: space-between;
		}

	}

	/* 翻页指示 */
	.page-turn-hint {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		font-size: 32rpx;
		color: #ccc;
		opacity: 0.7;
	}

	.page-turn-hint.left {
		right: 10rpx;
	}

	.page-turn-hint.right {
		left: 10rpx;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.notebook-container {
			width: 95%;
			height: fit-content;
			min-height: 750rpx;
			padding: 10px 0;

		}

		.left-page,
		.right-page {
			width: 640rpx;
		}

		.date-list {
			padding: 15rpx;
		}

		.content-area {
			padding: 15rpx;
		}
	}

	.noContent {
		font-size: 12px;
		color: #ccc;
	}

	.inputbox {
		font-size: 12px;
		color: #999
	}

	.my-button {
		font-size: 12px;
		width: 100rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
	}
</style>